package com.breadenglish.cms.api.app.gateway.interceptor;

import com.breadenglish.cms.api.app.common.context.PagingContextHolder;
import com.breadenglish.cms.api.app.common.page.Page;
import com.breadenglish.cms.api.app.common.page.QueryPage;
import com.breadenglish.cms.api.app.common.utils.StringUtils;
import com.breadenglish.cms.api.app.gateway.anotation.AppPaging;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;


/**
 * Spring 方法拦截器
 * User: guoyao
 * Date: 16-01-07
 * Time: 下午7:23
 */
@Service("appPagingInterceptor")
public class AppPagingInterceptor implements MethodInterceptor {

    private static Logger logger = LoggerFactory.getLogger(AppPagingInterceptor.class);


    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        HttpServletRequest request = null;
        // 判断是否是带有翻页注解
        if (invocation.getMethod().isAnnotationPresent(AppPaging.class)) {
            int page = -1;
            int pageSize = -1;
            for (Object obj : invocation.getArguments()) {
                if (Integer.class.isInstance(obj)) {
                    if (page == -1) {
                        page = (int) obj;
                        continue;
                    }
                    if (pageSize == -1){
                        pageSize = (int) obj;
                    }
                }
            }
            QueryPage queryPage = new QueryPage();
            queryPage.setPage(page);
            queryPage.setRows(pageSize);
            addContextHolder(getPage(queryPage));
        }
        // 方法处理
        Object result;
        try {
            result = invocation.proceed();
        } catch (Throwable t) {
            logger.debug("翻页方法处理异常！", t);
            throw t;
        } finally {
            clearContextHolder();
        }
        return result;
    }

    protected Page getPage(QueryPage queryPage) {
        Page rollPage = new Page();
        //当前页
        Integer page = queryPage.getPage();
        int currentPage = (page != null && page > 0 ? page : 1);
        rollPage.setCurrentPage(currentPage);
        //每页显示条数
        Integer rows = queryPage.getRows();
        int pageSize = (rows != null && rows > 0 ? rows : 10);
        rollPage.setPageSize(pageSize);
        return rollPage;
    }

    public void addContextHolder(Page rollPage) {
        // 设置翻页参数
        PagingContextHolder.setPage(rollPage);
    }

    public void clearContextHolder() {
        // 清理过期的翻页参数
        PagingContextHolder.removePage();
    }
}
